/*
 * @Author: zhangxin 
 * @Date: 2021-01-05 09:32:41 
 * @Last Modified by: zhangxin
 * @Last Modified time: 2021-02-25 10:12:30
 * 
 * 模版导入弹框
 */

import React, { useState,useEffect } from 'react'
import {
    Modal,
    Form,
    Upload,
    Button,
    message,
} from "antd"
import hcpUtils from "@/utils/hcpUtils";
import cmdbres from "@/data/cmdbres";
import request, { download } from "@/utils/request";
import "./index.less";

const user = hcpUtils.getUser();
const TempImportModal = (props)=>{
    const {
        visible,
        setVisible,
        onImportFinish,
        downloadApi, // 下载模板文件名
        downloadParam={},
        downloadURL,
        importApi, // 导入api及导入方法
        importParam={}, // 导入的额外参数
        maxSize=200 * 1024 * 1024,
        ...prop
    } = props

    const [form] = Form.useForm();
	const [fileList, setFileList] = useState([]);
    const [uploadDisabled, setUploadDisabled] = useState(false);
    const [downLoading, setDownLoading] = useState(false);
    const [loading, setLoading] = useState(false);
    const urlPre = cmdbres.cmdbBase;

    useEffect(() => {
        if(visible){
            setFileList([]);
            form.resetFields();
        }
    }, [visible])

    const handleBtnClick = async (e) => {
     //   if(!downloadApi){
     //       throw new Error("下载模板的文件名未传");
     //   }
     //   ...cmdbres.downloadExcelTemplate,
     //       params: param
     //   });
        setDownLoading(true);
        let paramStr = "";
        for (let item in downloadParam) {
            paramStr += item + "=" + downloadParam[item] + "&";
        }
        console.log(paramStr);
        const url = paramStr ? `${downloadURL}?${paramStr}` : `${downloadURL}`
        await download({ url: urlPre + url});
        setDownLoading(false);
    }

    const onFinish = async () => {
        if(!importApi){
            throw new Error("导入地址未传");
        }
        if(fileList.length !== 1) {
            message.error("必须上传一个文件！");
            return;
        }
        const formData = new FormData();
        formData.append('file', fileList[0]);
        // 额外参数处理
        const paramKeys = Object.keys(importParam);
        if(paramKeys.length > 0){
            paramKeys.forEach(item => {
                formData.append(item, importParam[item]);
            })
        }
        formData.append("author", user.staffName);
        setLoading(true);
        const res = await request({
            ...importApi,
            data: formData,
            headers: {
                "Content-Type":"multipart/form-data; boundary=----WebKitFormBoundaryweXIOplef1V0keZk",
            }
        });
        setLoading(false);
        if (res) {
            if(res.code == 200) {
                message.success("导入成功！");
                setVisible(false);
            }else if(res.code == 201 && res.data) {
                let mess = "";
                if(res.data.errorCount > 0) {
                    mess = res.data.errorMsg.join(";")
                }else {
                    mess = "导入"+ res.data.total +"条"
                    if(res.data.addCount != undefined) mess += "， 新增"+ res.data.addCount +"条"
                    if(res.data.updateCount != undefined) mess += "， 更新"+ res.data.updateCount +"条"
                    setVisible(false);
                }
                message.success(mess);
            }else {
                message.success(res.msg);
            }
            if(typeof onImportFinish == "function") onImportFinish(res,formData);
        }
    }

    const uploadProps = {
		name: 'file',
		// action: API_SERVER + action,
        method: "post",
        multiple: false,
        accept:".xls,.xlsx",
		headers: {
            ACCESS_TOKEN: hcpUtils.getToken(),
            token: hcpUtils.getToken(),
        },
        disabled:uploadDisabled,
        fileList:fileList,
        onRemove:(file) => {
            setFileList([]);
        },
        beforeUpload: (file,fileList) => {
            // 大小判断
            if (maxSize && file.size > maxSize) {
                message.error( `文件的大小${hcpUtils.bytesToSize(file.size)},不可超过${hcpUtils.bytesToSize(maxSize)}`);
            } else {
                setFileList(fileList);
                console.log(file,fileList)
            }
            return false;
        },
	};

    return (
        <Modal
			title="导入"
            className="hcp-modal-sm"
			visible={visible}
			footer={null}
			destroyOnClose
            onCancel={()=>{setVisible(false)}}
            {...prop}
		>
			<Form
				labelCol={{ span: 5 }}
                wrapperCol={{ span: 19 }}
                form={form}
				onFinish={onFinish}
			>
                <Form.Item
                    label="模板下载"
                >
                    <Button
                        style={{ height: 'auto', padding: '0 10px 0 0' }}
                        type="link"
                        loading={downLoading}
                        onClick={(e) => { handleBtnClick(e) }}
                    >
                        {downloadApi || '下载模板'}
                    </Button>
                </Form.Item>
                <Form.Item
                    label="上传文件"
                    name="importFile"
                    rules={[
                        {required:true,message:"请选择文件"}
                    ]}
                >
                    <div className="hcp_import_template">
                        <div className="hcp_import_div">
                            <Upload
                                {...uploadProps}
                            >
                                <span className="iconfont icon-shangchuanwenjian2"></span>
                                点击上传
                            </Upload>
                            <div className="description">{prop.description || ''}</div>
                        </div>
                    </div>
                </Form.Item>
                <div className="hcp-modal-body-footer">
                    <Form.Item wrapperCol={{ span: 24 }}>
                        <Button
                            onClick={()=>{setVisible(false)}}
                        >
                            取消
                        </Button>
                        <Button
                            type="primary" htmlType="submit" loading={loading}>
                            开始导入
                        </Button>
                    </Form.Item>
                </div>
			</Form>
		</Modal>
    )
}

export default TempImportModal